/**
 * Created by luckyjing on 15/12/22.
 */
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server).of('/node');
var client = require('./middle');
var config = require('./config');
app.enable('trust proxy');
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(config.path + '/static', express.static('static'));

// 测试模板数据是否可以显示在页面上
app.get(config.path + '/test', function (req, res) {
    var userInfo = {
        username: "测试",
        userid: 123
    };
    res.render('index', {
        username: userInfo.username,
        userid: userInfo.userid,
        headimgurl: "http://www.embeddedjs.com/images/star.png"
    });
});

app.get(config.path + "/getUser", function (req, res) {
    console.log('返回得到的code为' + req.query.code);
    client.getAccessToken(req.query.code, function (result) {
        var options = result;
        client.getUser(options, function (userInfo) {
            console.log(userInfo);
            res.set('Content-Type', 'text/html');
            res.render('index', {
                username: userInfo.nickname,
                userid: userInfo.userid,
                headimgurl: userInfo.headimgurl
            });
        });
    })
});
app.get(config.path + '/screen', function (req, res) {
    res.set('Content-Type', 'text/html');
    res.render('pc');
});
var onlineUsers = {};
var onlineCount = 0;
io.on('connection', function (socket) {
    console.log('用户加入');
    socket.on('login', function (obj) {
        socket.name = obj.userid;
        if (!onlineUsers.hasOwnProperty(obj.userid)) {
            onlineUsers[obj.userid] = obj.username;
            onlineCount++;
        }
        io.emit('login', {
            onlineUsers: onlineUsers,
            onlineCount: onlineCount,
            user: obj
        });
        console.log(obj.username + '加入了聊天室');
    });
    socket.on('discount', function () {
        if (onlineUsers.hasOwnProperty(socket.name)) {
            var obj = {
                userId: socket.name,
                userName: onlineUsers[socket.name]
            };
            delete onlineUsers[socket.name];
            onlineCount--;
            io.emit('logout', {
                onlineUsers: onlineUsers,
                onlineCount: onlineCount,
                user: obj
            });
            console.log(obj.userName + '退出了聊天室');
        }
    });
    socket.on('message', function (obj) {
        console.log(obj);
        io.emit('message', obj);
        console.log(obj.username + "说：" + obj.content);
    });
    socket.on('chat message', function (obj) {
        console.log(obj);
    })
});

server.listen(3000, function () {
    console.log('listening on 3000');
});
